/**
 *  This file is part of AugeasWH.
 *
 *  AugeasWH. is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AugeasWH. is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AugeasWH.  If not, see <http://www.gnu.org/licenses/>.
 */

package cz.fit.vutbr.pis2012.augeaswh.control;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cz.fit.vutbr.pis2012.augeaswh.control.authentication.AccessRightManager;
import cz.fit.vutbr.pis2012.augeaswh.persistence.User;

public class RestrictAdminFilter implements Filter {

	private FilterConfig fc;
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpRequest.getSession();
		String pageRequested = httpRequest.getRequestURL().toString();
		User loggedUser = (User) session.getAttribute("loggedUser");
		
		// Podmienka na zafiltrovanie
		if (filterRequest(loggedUser, pageRequested)) {
			httpResponse.sendRedirect("../login.xhtml");
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig fc) throws ServletException {
		this.fc = fc;
	}
	
	/**
	 * Metoda zapuzdrujuca podmienku ci filtrovat poziadavok alebo nie
	 * @param user uzivatel
	 * @param pageRequested zobrazovana stranka
	 * @return true ak zafiltrovat inak false
	 */
	private boolean filterRequest(User user, String pageRequested) {
		boolean isAdminSection = pageRequested.contains("admin") || pageRequested.contains("ekonom") || pageRequested.contains("whman");
		boolean isUser = user != null;
		if (!isAdminSection) 
			return false;
		return !isUser || !AccessRightManager.hasRightToViewPage(user, pageRequested);
	}

}
